<template>
  <!-- 列表 align="center" -->
  <ContentWrap>
    <el-table :data="list" :stripe="true" :show-overflow-tooltip="true"
              :default-sort = "{prop: 'itemNo', order: 'descending'}">
      <el-table-column label="序号" align="center" type="index" width="60" fixed="left"/>
      <el-table-column align="center" label="部件名称" fixed="left" prop="itemName" min-width="120" sortable/>
      <el-table-column label="部件代码" align="center" prop="itemNo" width="min-100"  sortable/>
      <el-table-column label="规格" align="center" prop="itemDimension" width="min-100"  />
      <el-table-column label="数量" align="center" prop="itemCount" width="min-80" sortable>
        <template #default="scope"  >
          <el-input-number
            v-if="scope.row.editing"
            v-model="scope.row.itemCount"
            controls-position="right"
            @blur="saveEdit(scope.row)"
            :min="1"
            :precision="3"
            class="!w-80%"
          />
<!--          <el-input-->
<!--            v-if="scope.row.editing"-->
<!--            v-model="scope.row.itemCount"-->
<!--            @blur="saveEdit(scope.row)"-->
<!--          />-->
          <span v-else  @dblclick="startEdit(scope.row)">
            {{ scope.row.itemCount }} <dict-tag :type="DICT_TYPE.CRM_PRODUCT_UNIT" :value="scope.row.itemUnit" />
          </span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="itemStatus" width="100" >
        <!--用插槽包裹el-switch开关-->
        <template #default="scope">
          <el-switch active-text="开启" :active-value=1 active-color="#2fa1f1" inactive-text="关闭"
                     :inactive-value=0 inactive-color="#9c9c9c" v-model="scope.row.itemStatus"
                     @change="handleStatusChange(scope.row)"/>
          <!--当tradingVolumeStatus=1时switch开启，当tradingVolumeStatus=0时switch关闭-->
        </template><!--回显的时候 int类型使用 ：active-value，字符串类型不加引号-->
      </el-table-column>
      <el-table-column label="备注" align="center" prop="note" width="min-120" >
        <template #default="scope">
          <el-input v-if="scope.row.editing"  v-model="scope.row.note"
            @blur="saveEdit(scope.row)" />
          <span v-else @dblclick="startEdit(scope.row)" >{{ scope.row.note }}</span>
        </template>
      </el-table-column>
<!--      v-if="row.itemStatus === 10|| row.itemStatus === 0"-->
      <el-table-column label="操作" align="center" fixed="right" width="240">
<!--        <template #default="{ $index }">-->
<!--          <el-button type='primary'  text @click="editRow(row, $index)">编辑1</el-button>-->
<!--          <el-button type="primary" text @click="saveRow(row, $index)">保存</el-button>-->
<!--        </template>-->
        <template #default="scope">
          <el-button v-if="!scope.row.editing"  @click="startEdit(scope.row)"  > 编辑 </el-button>
          <el-button v-if="scope.row.editing" type="success" @click="saveEdit(scope.row)"  > 保存 </el-button>
<!--          <el-button  link type="primary"-->
<!--            @click="editForm('update',scope.row.id)"-->
<!--            v-hasPermi="['crm:product:update']" > 编辑  </el-button>-->
          <el-button  link type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['crm:product:update']"  > 删除  </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions ,getStrDictOptions} from '@/utils/dict'
import * as ContractApi from '@/api/crm/contract'
import { useRouter } from 'vue-router';

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const loading = ref(true) // 加载中
const rowEditing = ref(false) // 加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据

const startEdit = (row) => {
  row.editing = true
  rowEditing.value = true
  this.$nextTick(() => {
    // 自动聚焦输入框
    this.$el.querySelector('input')?.focus()
  })
}

const saveEdit = async(row) => {
  row.editing = false
  console.log('保存数据:', row)
  await message.confirm("您确定要修改部件：["+row.itemName+"]的信息吗？");
  await ContractApi.updateContractItem(row)
  // 保存数据到后端
  message.success(t('common.updateSuccess'))
  // 刷新列表
  await forceRerender()
}

const props = defineProps<{
  contractId?: number // 订单id（主表的关联字段）
  productId?: number // 产品id（主表的关联字段）
}>()

const rules = ({
  key: [{ required: true, message: '请输入', trigger: 'blur' }],
  value: [{ required: true, message: '请输入', trigger: 'blur' }],
})

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  productId: undefined as unknown, // 允许 undefined + number
  contractId: undefined as unknown // 允许 undefined + number
})
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 置空参数
    queryParams.contractId = undefined
    queryParams.productId = undefined
    queryParams.contractId = props.contractId
    queryParams.productId = props.productId
    const data =  await ContractApi.getContractItemlist(queryParams)
    list.value = data
    total.value = data.length
  } finally {
    loading.value = false
  }
}

// 刷新页面
const router = useRouter();
const forceRerender = () => {
  router.go(0);

};

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    // await ContractApi.deleteContractItem(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await forceRerender()
  } catch {
    message.error('删除操作失败，请您重新操作！')
  }
}

const handleStatusChange = async (row) => {
  try {
    // 修改状态
    await message.confirm("您确定要修改过["+row.itemName+"]的状态吗？");
    await ContractApi.updateContractItem(row)
    message.success(t('common.updateSuccess'))
    // 刷新列表
    await forceRerender()
  } catch {
    // message.error('删除操作失败，请您重新操作！')
  }
}

/** 打开详情 */
const { currentRoute, push } = useRouter()
const openDetail = (id: number) => {
  push({ name: 'CrmProductDetail', params: { id } })
}
/** 初始化 **/
onMounted(() => {
  getList()
})

</script>
